<?php


namespace app\user\controller;


use app\user\logic\ShareLinkLogic;
use EasyWeChat\Factory;
use think\Controller;
use think\facade\Config;

class Wechat extends Controller
{

    //更新链接
    private function updateUrl($app_id,$msg_id,$url){

        $link=\app\common\model\WechatShareLink::where([
            'app_id'=>$app_id,
            'msg_id'=>$msg_id
        ])->find();

        //判断是否存在该链接，存在就修改
        if($link){
//            $link->url=$url;
            $link->url=   str_replace("http","https","$url");
            $link->save();
        }
    }

    //消息
    public function index()
    {


        $app = Factory::officialAccount(ShareLinkLogic::getAccount());
//        $list= $app->user->list();  // $nextOpenId 可选

        $app->server->push(function ($message) {
            setLog($message->MsgType,json_encode($message));
            switch ($message->MsgType) {
                case 'event':
                    setLog("ArticleUrlResult",json_encode($message->ArticleUrlResult));
                    setLog("ArticleUrl",($message->ArticleUrlResult->ResultList->item->ArticleUrl));
                    setLog("MsgID",($message->MsgID));
                    $config=ShareLinkLogic::getAccount();
                    $this->updateUrl($config['app_id'],$message->MsgID,$message->ArticleUrlResult->ResultList->item->ArticleUrl);
                    return '收到事件消息';
                    break;
                case 'text':
                    return '收到文字消息132';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        $response = $app->server->serve();

        $response->send(); exit; // Laravel 里请使用：return $response;
    }

}
